import React, { useState, useEffect } from 'react'
import { Layout, Button, Modal } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import '../style/home.scss'
import { Outlet } from 'react-router-dom'
import LeftMenu from '../components/LeftMenu.jsx'
import withRouter from '../hooks/withRouter'

const { Sider, Content, Header } = Layout

function Home (props) {
  const token = sessionStorage.getItem('token')
  const userInfo = sessionStorage.getItem('userInfo')
  const [collapsed, setCollapsed] = useState(false)

  useEffect(() => {
    // 模拟componentDidMount，即只运行一次该函数
    if (!token) {
      window.loginOut()
    }
    document.title = '后台管理系统'
  }, [])

  const loginOut = () => {
    Modal.confirm({
      title: '操作确认',
      icon: <ExclamationCircleOutlined />,
      content: '确定退出登录吗？',
      okText: '确认',
      cancelText: '取消',
      maskClosable: true,
      onOk: () => {
        window.loginOut()
      }
    })
  }

  return (
    <Layout>
      <Header className='con-header'>
        <div className='title'>后台管理系统</div>
        <div className="right">
          <div className="info-user">
            你好，{userInfo.username || '--'}
          </div>
          <Button
            type="link"
            shape="round"
            size='small'
            onClick={() => loginOut()}>退出登录</Button>
        </div>
      </Header>
      <Layout>
        <Sider
          collapsible 
          collapsed={collapsed}
          collapsedWidth={55}
          onCollapse={value => setCollapsed(value)}>
          <LeftMenu />
        </Sider>
        <Content className='con-outlet'>
          {/* 自己组件的内容, 留给子组件Child的出口 */}
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  )
}

export default withRouter(Home)
